<template>
  <div class="invoice-setting">
    <section class="header">
      <a-page-header title="发票设置">
        <div class="page-desc">
          此处生成供开发票的模板。对账单进行开票时，发票模板需要支持对应的费用类型才能进行开票，请在税率规则中进行费用类型的配置并应用于发票模板。
        </div>
        <template #footer>
          <a-tabs v-model:active-key="activeTab">
            <a-tab-pane
              v-for="tab of TABLIST"
              :key="tab.key"
              :tab="tab.title"
            />
            <template #rightExtra>
              <a-button
                style="margin-bottom: 5px"
                @click="invoiceParametersClick"
                v-permission="[
                  'InvoiceSetting',
                  'auth',
                  'electronInvoiceSetting',
                ]"
              >
                电子发票参数
              </a-button>
            </template>
          </a-tabs>
        </template>
      </a-page-header>
    </section>
    <section class="content">
      <a-row :gutter="[12, 12]" v-show="activeTab == 'setting'">
        <a-col :span="12">
          <a-card title="售方信息">
            <template #extra>
              <a-button type="primary" @click="addOrEditSeller()">
                <template #icon>
                  <PlusOutlined />
                </template>
                新建售方信息
              </a-button>
            </template>
            <div class="card-content">
              <a-table
                :columns="SELLERCOLUMN"
                :data-source="sellerList"
                row-key="id"
                :pagination="sellerPagination"
                @change="handleSellerTableChange"
              >
                <template #bodyCell="{ text, record, index, column }">
                  <template v-if="column.key === 'company_name'">
                    <span>{{ text }}</span>
                    <a-tag
                      color="blue"
                      style="margin-left: 4px"
                      v-if="record.is_old_data == 1"
                    >
                      需编辑
                    </a-tag>
                  </template>
                  <template v-if="column.key === 'action'">
                    <a-button type="link" @click="addOrEditSeller(text)">
                      编辑
                    </a-button>
                    <a-button type="link" danger @click="removeSeller(text)">
                      删除
                    </a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="税收分类编码">
            <template #extra>
              <a-button type="primary" @click="addOrEditTaxCode()">
                <template #icon>
                  <PlusOutlined />
                </template>
                新建税收分类编码
              </a-button>
            </template>
            <div class="card-content">
              <a-table
                :columns="TAXCODECOLUMN"
                :data-source="taxCodeList"
                row-key="id"
                :pagination="taxCodePagination"
                @change="handleTaxCodeTableChange"
              >
                <template #bodyCell="{ text, record, index, column }">
                  <template v-if="column.key === 'rate'">
                    <span>{{ text }}%</span>
                  </template>
                  <template v-if="column.key === 'action'">
                    <a-button type="link" @click="addOrEditTaxCode(text)">
                      编辑
                    </a-button>
                    <a-button type="link" danger @click="removeTaxCode(text)">
                      删除
                    </a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </a-card>
        </a-col>
        <a-col :span="24">
          <a-card title="税率规则">
            <template #extra>
              <a-button type="primary" @click="addOrEditTaxRate()">
                <template #icon>
                  <PlusOutlined />
                </template>
                新建税率规则
              </a-button>
            </template>
            <a-table
              :columns="TAXRATECOLUMN"
              :data-source="taxRateList"
              row-key="id"
              :pagination="taxRatePagination"
              @change="handleTaxRateTableChange"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'code'">
                  <span>{{ text.tax_code }}</span>
                </template>
                <template v-if="column.key === 'rate'">
                  <span>{{ text.tax_rate }}%</span>
                </template>
                <template v-if="column.key === 'status'">
                  <a-switch
                    checked-children="开"
                    un-checked-children="关"
                    :checked="text"
                    :checkedValue="1"
                    :unCheckedValue="0"
                    @change="
                      (checked) => handleTaxRuleStatusChange(checked, record.id)
                    "
                  />
                </template>
                <template v-if="column.key === 'action'">
                  <a-button type="link" @click="addOrEditTaxRate(text)">
                    编辑
                  </a-button>
                  <a-button type="link" danger @click="removeTaxRate(text)">
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
      <section v-show="activeTab == 'template'" class="invoice-template">
        <a-row :gutter="[12, 12]">
          <a-col :xs="24" :md="12" :xxl="8" class="box add-box">
            <a-card :bordered="false" class="card" @click="addOrEditInvoice()">
              <PlusOutlined />
              <span class="ml-10">新增模板</span>
            </a-card>
          </a-col>
          <a-col
            :xs="24"
            :md="12"
            :xxl="8"
            class="box"
            v-for="invoice of invoiceList"
            :key="invoice.arrKey"
          >
            <a-card class="card">
              <a-row class="info">
                <a-col :span="4">
                  <cu-icon type="org-fapiao" class="icon"></cu-icon>
                </a-col>
                <a-col :span="20">
                  <a-row class="invoice-name">{{ invoice.name }}</a-row>
                  <a-row class="invoice-info">
                    <a-col :span="6">售方名称：</a-col>
                    <a-col :span="18" class="nowrap">{{
                      invoice.seller_name
                    }}</a-col>
                  </a-row>
                  <a-row class="invoice-info">
                    <a-col :span="6">应用楼宇：</a-col>
                    <a-col :span="18" class="nowrap">
                      <a-tooltip>
                        <template #title
                          ><span>{{ invoice.build_names }}</span></template
                        >
                        {{ invoice.build_names }}
                      </a-tooltip>
                    </a-col>
                  </a-row>
                  <a-row class="invoice-info">
                    <a-col :span="6">税率规则：</a-col>
                    <a-col :span="18" class="nowrap">
                      <a-tooltip>
                        <template #title>
                          <span
                            v-for="item of invoice.tax_rules"
                            :key="item.id"
                            class="mr-10"
                          >
                            {{ item.cost_type_txt }}
                            ({{ item.tax_code_data.tax_rate_txt }})
                          </span>
                        </template>
                        <a-tag
                          v-for="item of invoice.tax_rules"
                          :key="item.id"
                          color="blue"
                          class="mr-10"
                        >
                          {{ item.cost_type_txt }}({{
                            item.tax_code_data.tax_rate_txt
                          }})
                        </a-tag>
                      </a-tooltip>
                    </a-col>
                  </a-row>
                </a-col>
              </a-row>
              <template #actions>
                <EditOutlined
                  @click="addOrEditInvoice(invoice.id)"
                  style="color: #2681f3"
                  key="edit"
                />
                <DeleteOutlined
                  @click="removeInvoice(invoice.id)"
                  style="color: #f5222d"
                  key="delete"
                />
              </template>
            </a-card>
          </a-col>
          <a-col :span="24" class="text-right mt-10">
            <a-pagination
              show-size-changer
              v-model:current="invoicePage"
              v-model:pageSize="invoicePageSize"
              :total="invoicePageTotal"
              @showSizeChange="getInvoiceList"
              @change="getInvoiceList"
            />
          </a-col>
        </a-row>
      </section>
    </section>

    <!-- 添加编辑 -->
    <add-seller
      :visible="sellerAddVisible"
      :id="sellerId"
      @cancel="sellerAddVisible = false"
      @success="sellerAddSuccess"
    />
    <add-tax-code
      :visible="taxCodeAddVisible"
      :id="taxCodeId"
      @cancel="taxCodeAddVisible = false"
      @success="taxCodeAddSuccess"
    />
    <add-tax-rate
      :visible="taxRateAddVisible"
      :id="taxRateId"
      @cancel="taxRateAddVisible = false"
      @success="taxRateAddSuccess"
    />
    <add-invoice-temp
      :visible="invoiceAddVisible"
      :id="invoiceId"
      @cancel="invoiceAddVisible = false"
      @success="invoiceAddSuccess"
    />
    <InvoiceParameters
      :visible="invoiceParametersVisible"
      @cancel="invoiceParametersVisible = false"
      @success="onInvoiceSuccess"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed } from "vue";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import { message } from "ant-design-vue";
import AddSeller from "./modules/addSeller.vue";
import AddTaxCode from "./modules/addTaxCode.vue";
import AddTaxRate from "./modules/addTaxRate.vue";
import AddInvoiceTemp from "./modules/addInvoiceTemp.vue";
import { useRoute } from "vue-router";
import InvoiceParameters from "./modules/invoiceParameters.vue";

export default defineComponent({
  name: "InvoiceSetting",
  components: {
    AddSeller,
    AddTaxCode,
    AddTaxRate,
    AddInvoiceTemp,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    InvoiceParameters,
  },
  setup() {
    const $route = useRoute();

    const state = reactive({
      activeTab: "",
      // 1、售方信息
      sellerPage: 1,
      sellerPageSize: 10,
      sellerPageTotal: 0,
      sellerList: [],
      sellerAddVisible: false,
      sellerId: 0,
      // 2、税收分类
      taxCodePage: 1,
      taxCodePageSize: 10,
      taxCodePageTotal: 0,
      taxCodeList: [],
      taxCodeAddVisible: false,
      taxCodeId: 0,
      // 3、税率规则
      taxRatePage: 1,
      taxRatePageSize: 10,
      taxRatePageTotal: 0,
      taxRateList: [],
      taxRateAddVisible: false,
      taxRateId: 0,
      // 4、发票模板
      invoiceAddVisible: false,
      invoiceId: 0,
      invoicePage: 1,
      invoicePageSize: 10,
      invoicePageTotal: 0,
      invoiceList: [],

      invoiceParametersVisible: false,
    });
    /* 1、售方信息 */
    const getSellerList = () => {
      request
        .get("/org", "/invoice/sellerList", {
          page: state.sellerPage,
          limit: state.sellerPageSize,
        })
        .then((res) => {
          state.sellerList = res.list;
          state.sellerPageTotal = res.total;
        });
    };
    const sellerPagination = computed(() => ({
      total: state.sellerPageTotal,
      current: state.sellerPage,
      pageSize: state.sellerPageSize,
      showSizeChanger: true,
    }));
    const handleSellerTableChange = (pager) => {
      state.sellerPage = pager.current;
      state.sellerPageSize = pager.pageSize;
      getSellerList();
    };
    const addOrEditSeller = (id) => {
      state.sellerId = id || 0;
      state.sellerAddVisible = true;
    };
    const sellerAddSuccess = () => {
      state.sellerAddVisible = false;
      getSellerList();
    };
    const removeSeller = (id) => {
      utils.modalConfirm({
        content: "确认要删除本条售方信息吗？",
        okType: "danger",
        centered: true,
        onOk: () => {
          request
            .del("/org", "/invoice/sellerDel", { id, needMsg: true })
            .then((res) => {
              message.success(res.msg || "删除成功");
              getSellerList();
            });
        },
      });
    };
    /* 2、税收分类 */
    const getTaxCodeList = () => {
      request
        .get("/org", "/invoice/codeList", {
          page: state.taxCodePage,
          limit: state.taxCodePageSize,
        })
        .then((res) => {
          state.taxCodeList = res.list;
          state.taxCodePageTotal = res.total;
        });
    };
    const taxCodePagination = computed(() => ({
      total: state.taxCodePageTotal,
      current: state.taxCodePage,
      pageSize: state.taxCodePageSize,
      showSizeChanger: true,
    }));
    const handleTaxCodeTableChange = (pager) => {
      state.taxCodePage = pager.current;
      state.taxCodePageSize = pager.pageSize;
      getTaxCodeList();
    };
    const addOrEditTaxCode = (id) => {
      state.taxCodeId = id || 0;
      state.taxCodeAddVisible = true;
    };
    const taxCodeAddSuccess = () => {
      state.taxCodeAddVisible = false;
      getTaxCodeList();
      getTaxRateList();
    };
    const removeTaxCode = (id) => {
      utils.modalConfirm({
        content: "确认要删除本条税收分类吗？",
        okType: "danger",
        centered: true,
        onOk: () => {
          request
            .del("/org", "/invoice/codeDel", { id, needMsg: true })
            .then((res) => {
              message.success(res.msg || "删除成功");
              getTaxCodeList();
            });
        },
      });
    };
    /* 3、税率规则 */
    const getTaxRateList = () => {
      request
        .get("/org", "/invoice/taxRule", {
          page: state.taxRatePage,
          limit: state.taxRatePageSize,
        })
        .then((res) => {
          state.taxRateList = res.list;
          state.taxRatePageTotal = res.total;
        });
    };
    const taxRatePagination = computed(() => ({
      total: state.taxRatePageTotal,
      current: state.taxRatePage,
      pageSize: state.taxRatePageSize,
      showSizeChanger: true,
    }));
    const handleTaxRateTableChange = (pager) => {
      state.taxRatePage = pager.current;
      state.taxRatePageSize = pager.pageSize;
      getTaxRateList();
    };
    const addOrEditTaxRate = (id) => {
      state.taxRateId = id || 0;
      state.taxRateAddVisible = true;
    };
    const taxRateAddSuccess = () => {
      state.taxRateAddVisible = false;
      getTaxRateList();
    };
    const removeTaxRate = (id) => {
      utils.modalConfirm({
        content: "确认要删除本条税率规则吗？",
        okType: "danger",
        centered: true,
        onOk: () => {
          request
            .del("/org", "/invoice/taxRuleDel", { id, needMsg: true })
            .then((res) => {
              message.success(res.msg || "删除成功");
              getTaxRateList();
            });
        },
      });
    };
    const handleTaxRuleStatusChange = (status, id) => {
      request
        .put("/org", "/invoice/updateStatus", {
          id,
          status,
          needMsg: true,
        })
        .then((res) => {
          message.success(res.msg || "操作成功！");
          getTaxRateList();
        });
    };
    /* 4、发票模板 */
    const getInvoiceList = () => {
      request
        .get("/org", "/invoice/templateList", {
          page: state.invoicePage,
          limit: state.invoicePageSize,
        })
        .then((res) => {
          state.invoiceList = res.list;
          state.invoicePageTotal = res.total;
        });
    };
    const addOrEditInvoice = (id) => {
      state.invoiceId = id || 0;
      state.invoiceAddVisible = true;
    };
    const invoiceAddSuccess = () => {
      state.invoiceAddVisible = false;
      getInvoiceList();
    };
    const removeInvoice = (id) => {
      utils.modalConfirm({
        content: "确认要删除本条发票模板吗？",
        okType: "danger",
        centered: true,
        onOk: () => {
          request
            .del("/org", "/invoice/template", { id, needMsg: true })
            .then((res) => {
              message.success(res.msg || "删除成功");
              getInvoiceList();
            });
        },
      });
    };

    // 电子发票参数
    const invoiceParametersClick = () => {
      state.invoiceParametersVisible = true;
    };

    const onInvoiceSuccess = () => {
      state.invoiceParametersVisible = false;
    };

    const init = () => {
      state.activeTab = $route.query.type || TABLIST[0].key;
      getSellerList();
      getTaxCodeList();
      getTaxRateList();
      getInvoiceList();
    };

    init();

    return {
      TABLIST,
      SELLERCOLUMN,
      TAXCODECOLUMN,
      TAXRATECOLUMN,
      sellerPagination,
      taxCodePagination,
      taxRatePagination,
      ...toRefs(state),
      addOrEditSeller,
      sellerAddSuccess,
      handleSellerTableChange,
      removeSeller,
      handleTaxCodeTableChange,
      addOrEditTaxCode,
      taxCodeAddSuccess,
      removeTaxCode,
      handleTaxRateTableChange,
      addOrEditTaxRate,
      taxRateAddSuccess,
      removeTaxRate,
      handleTaxRuleStatusChange,
      invoiceAddSuccess,
      addOrEditInvoice,
      getInvoiceList,
      removeInvoice,
      onInvoiceSuccess,
      invoiceParametersClick,
    };
  },
});

const TABLIST = [
  { title: "相关设置", key: "setting" },
  { title: "发票模板", key: "template" },
];
const SELLERCOLUMN = [
  {
    title: "公司名称",
    dataIndex: "company_name",
    key: "company_name",
  },
  {
    title: "开户行",
    dataIndex: "bank",
    key: "bank",
  },
  {
    title: "电话",
    dataIndex: "phone",
    key: "phone",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];
const TAXCODECOLUMN = [
  {
    title: "商品或服务名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "税收分类编码",
    dataIndex: "tax_code",
    key: "tax_code",
  },
  {
    title: "税率",
    dataIndex: "tax_rate",
    key: "rate",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];
const TAXRATECOLUMN = [
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
  },
  {
    title: "税收分类编码",
    dataIndex: "tax_code_data",
    key: "code",
  },
  {
    title: "税率",
    dataIndex: "tax_code_data",
    key: "rate",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];
</script>

<style lang="less" scoped>
.invoice-setting {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .header {
    background: #fff;
    margin-left: 1px;
    &:deep(.ant-tabs-bar) {
      margin: 0;
    }
  }
  .content {
    flex: 1;
    padding: 10px;
    overflow: hidden auto;
    .card-content {
      height: 450px;
      overflow: hidden auto;
    }
    .invoice-template {
      background: #fff;
      height: 100%;
      overflow: hidden auto;
      padding: 10px 20px;
      .add-box {
        border: 1px dashed #ddd;
        cursor: pointer;
        .card {
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 20px;
          color: #999;
        }
      }
      .box {
        border-radius: 8px;
        height: 260px;

        .card {
          width: 100%;
          height: 100%;
          .info {
            height: 160px;

            .icon {
              font-size: 48px;
              color: @primary-color;
            }
            .invoice-name {
              font-size: 20px;
              font-weight: bold;
              padding-bottom: 10px;
            }
            .invoice-info {
              color: #666;
              line-height: 40px;
            }
          }
        }
      }
    }
  }
}
</style>
